package com.hxzy.controller.upload;


import com.hxzy.common.enums.AckCode;
import com.hxzy.common.resp.R;
import com.hxzy.config.MinioConfig;
import com.hxzy.util.MinioUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.StorageClass;
import com.qcloud.cos.region.Region;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @Author wy
 * @Description minio文件上传
 * @Date 2023/4/14 11:15
 * @Version 1.0
 */
@Api(tags = "Minio文件上传API")
@RestController
@RequestMapping(value = {"/api/minio/upload","/front/minio/upload"})
public class MinioUploadController {

    @Resource
    private MinioUtil minioUtil;

    @Resource
    private MinioConfig minioConfig;



    @ApiOperation(value = "图片上传，只支持(png,jpg,gif)")
    @PostMapping(value = "/image")
    @ApiImplicitParam(name = "file",value = "上传文件到本地",required = true,dataType="MultipartFile",dataTypeClass = MultipartFile.class,paramType = "query")
    public R imageUpload(@RequestPart MultipartFile file) throws IOException {
        if(file.isEmpty()){
            return R.build(AckCode.FILE_NOT_EMPTY);
        }

        //上传文件的名称
        String originalFileName=file.getOriginalFilename();
        //得到文件扩展名
        int lastIndex=originalFileName.lastIndexOf(".");
        if(lastIndex<=0){
            return R.build(AckCode.UPLOAD_TYPE_ERROR);
        }

        String ext=originalFileName.substring(lastIndex);

        boolean contains = Arrays.asList(".png", ".jpg", ".jpeg").contains(ext.toLowerCase(Locale.ROOT));
        if(!contains){
            return R.build(AckCode.UPLOAD_TYPE_ERROR_IMAGE);
        }

        try {
            String uploadUrl= minioUtil.uploadFile(minioConfig.getBucketName(),file);
            //自定义返回结果
            Map<String,String> dataMap=new HashMap<>();
            dataMap.put("image_url", uploadUrl);
            dataMap.put("file_name",originalFileName);

            return R.okHasData(dataMap);

        } catch ( Exception e) {
            e.printStackTrace();
        }
        return R.build(AckCode.FAIL);
    }

}
